<script setup>
import { ref } from 'vue'
import useUserInfoStore from '@/stores/userInfo';
import avatar from '@/assets/default.png'
import { Plus } from '@element-plus/icons-vue'
const userInfoStore = useUserInfoStore();

//导入token
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();

const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, max: 16, message: '长度在 5 到 16 个字符', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9]+$/, message: '用户名只能是数字和字母组合', trigger: 'blur' }
    ],
    name: [{ required: true, message: '请输入用户昵称', trigger: 'blur' },
        { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
    ]
}
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    title: '',
    status: ''
})
const userModel = ref({
    id: null,
    username: null,
    name: null,
    password: null,
    email: null,
    phone: null,
    avatarUrl: null,
    role: null,
    status: null
})
const users = ref([])
//修改用户基本信息
import { userInfoUpdateService, userListService, addAdminService } from '@/api/user';
import { ElMessage, ElMessageBox } from 'element-plus';
//更新用户数据
const handleEdit = async (row) => {
    userModel.value = row;

    const action = row.status === 1 ? '禁用' : '启用';
    const message = `确认${action}${row.name}吗？`;

    ElMessageBox.confirm(
        message,
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            userModel.value.status = row.status === 1 ? 0 : 1;
            let result = await userInfoUpdateService(userModel.value);
            ElMessage({
                type: 'success',
                message: `${action}${row.name}成功`,
            });
            // 刷新列表
            getUserList();
            reset();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消操作',
            });
        });
};
const reset = () => {
    userModel.value = {
        id: null,
        username: null,
        name: null,
        password: null,
        email: null,
        phone: null,
        avatarUrl: null,
        role: null,
        status: null
    }
}
//获取用户列表
const getUserList = async () => {
    let result = await userListService(queryParams.value)
    users.value = result.data.items;
    total.value = result.data.total;
}
getUserList();

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    queryParams.value.pageSize = 10;
    getUserList();
}
// 重置按钮操作
function resetQuery() {
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        username: '',
        name: '',
        status: ''
    }
    getUserList();
}

//控制表单
const visibleDrawer = ref(false)

//分页条数据模型
const total = ref(20)//总条数


//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    queryParams.value.pageSize = size
    getUserList();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    queryParams.value.pageNum = num
    getUserList();
}
//添加管理员
const addAdmin = async () => {
    let result = await addAdminService(userModel.value);
    ElMessage({
        type: 'success',
        message: '添加成功',
    });
    // 刷新列表
    getUserList();
    visibleDrawer.value = false;
}
//上传成功的回调函数
const uploadSuccess = (result) => {
    userModel.value.avatarUrl = result.data;
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>用户管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true; reset(); title = '添加管理员'">添加管理员</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline :model="queryParams" ref="queryRef">
            <el-form-item label="用户账号：" style="width: 180px;">
                <el-input v-model="queryParams.username" placeholder="请输入账号"></el-input>
            </el-form-item>
            <el-form-item label="用户昵称：" style="width: 180px;">
                <el-input v-model="queryParams.name" placeholder="请输入昵称"></el-input>
            </el-form-item>
            <el-form-item label="用户状态：" style="width: 180px;">
                <el-select placeholder="请选择" v-model="queryParams.status">
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="禁用" value="0"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <el-form>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 用户列表 -->
        <el-table :data="users" style="width: 100%">
            <el-table-column type="index" width="50px" label="序号" align="center"></el-table-column>
            <el-table-column label="用户账号" prop="username"></el-table-column>
            <el-table-column label="用户昵称" prop="name"></el-table-column>
            <el-table-column label="用户邮箱" prop="email"></el-table-column>
            <el-table-column label="手机号" prop="phone"></el-table-column>
            <el-table-column label="用户状态" prop="status">
                <template #default="scope">
                    <el-tag v-if="scope.row.status == 1" type="success">启用</el-tag>
                    <el-tag v-else-if="scope.row.status == 0" type="warning">禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200px">
                <template #default="scope">
                    <el-button type="text"
                        @click="handleEdit(scope.row)">
                        {{ scope.row.status == 1 ? '禁用' : '启用' }}
                    </el-button>
                </template>
            </el-table-column>

            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 15, 20, 30]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
            
        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="30%">
            <el-form :model="userModel" :rules="rules">
                <el-form-item label="用户账号：" prop="username">
                    <el-input v-model="userModel.username" placeholder="请输入账号"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称：" prop="name">
                    <el-input v-model="userModel.name" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <!-- 头像 -->
                <el-form-item label="头像">
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :headers="{ 'Authorization': tokenStore.token }" :on-success="uploadSuccess">
                        <img v-if="userModel.avatarUrl" :src="userModel.avatarUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <!-- 选择用户角色 -->
                 <el-form-item label="用户角色：" prop="role">
                    <el-select v-model="userModel.role" placeholder="请选择">
                        <el-option label="管理员" value="1"></el-option>
                        <el-option label="超级管理员" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 确认添加 -->
                 <el-form-item>
                    <el-button type="primary" @click="addAdmin" style="margin-left: auto;">确认添加</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>